import { schema } from '@/ts/base';
import { Tree } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import React, { ReactNode, useState } from 'react';
import { AiOutlineAppstore, AiOutlineBorder } from 'react-icons/ai';
import cls from './ReportTree.module.less';
import { NodeType } from '@/ts/base/enum';

interface IProps<T extends schema.XReportTreeNode> {
  nodes: T[];
  onCheck?: TreeProps<T>['onCheck'];
  onSelect?: TreeProps<T>['onSelect'];
  onExpand?: TreeProps<T>['onExpand'];
  expandedKeys?: TreeProps['expandedKeys'];
  selectedKeys?: TreeProps['selectedKeys'];
  checkable?: TreeProps['checkable'];
  renderNode?: (node: T) => ReactNode;
}

/*
  报表左侧树
*/
const ReportTree = <T extends schema.XReportTreeNode = schema.XReportTreeNode>(
  props: IProps<T>,
) => {
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>(props.selectedKeys ?? []);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(props.expandedKeys ?? []);

  const treeTitleRender = (node: T) => {
    const treeIconRender = () => {
      switch (node.nodeType) {
        case NodeType.Normal:
          return (
            <AiOutlineBorder
              title={node.nodeTypeName}
              style={{ backgroundColor: '#DCDCDC' }}
            />
          );
        case NodeType.Summary:
        case NodeType.Balance:
          return <AiOutlineAppstore title={node.nodeTypeName}></AiOutlineAppstore>;
        default:
          return <div></div>;
      }
    };
    return (
      <div className={cls['tree-title-wrapper']}>
        <div className={cls['tree-title-icon']}>{treeIconRender()}</div>
        <div className={cls['tree-title']}>{props.renderNode?.(node) ?? node.name}</div>
      </div>
    );
  };

  return (
    <Tree<T>
      fieldNames={{ title: 'name', key: 'id', children: 'children' }}
      treeData={props.nodes}
      titleRender={treeTitleRender}
      expandedKeys={expandedKeys}
      onExpand={(keys, info) => {
        setExpandedKeys(keys);
        props?.onExpand && props.onExpand(keys, info);
      }}
      selectedKeys={selectedKeys}
      onSelect={(keys, info) => {
        setSelectedKeys(keys);
        props?.onSelect && props.onSelect(keys, info);
      }}
      checkable={props.checkable}
      onCheck={props.onCheck}
    />
  );
};

export default ReportTree;
